//
//  AccountInfoController.m
//  Kaiser
//
//  Created by Fidetro on 2017/1/3.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "AccountInfoController.h"
#import "YearToDayTableViewCell.h"
#import "SexTableViewCell.h"
#import "HeightTableViewCell.h"
#import "WeightTableViewCell.h"
#import "UserInfo.h"
#import "KaiseruserDataGit.h"
#import "SetUserInfoApi.h"
#import "BaseRequestController.h"
#import "BaseViewController+Camera.h"
#import "UIButton+WebCache.h"

@interface AccountInfoController ()<UITableViewDelegate,UITableViewDataSource>
/** topView **/
@property(nonatomic,strong) UIView *topView;
/** 头像 **/
@property(nonatomic,strong) UIButton *iconButton;
/** 你的名字 **/
@property(nonatomic,strong) UILabel *nicknameLabel;
/** 修改名字的按钮 **/
@property(nonatomic,strong) UIButton *editNameButton;
/** tableView **/
@property(nonatomic,strong) UITableView *tableView;
/** <#Description#> **/
@property(nonatomic,strong) NSArray *settingPlist;

@property (nonatomic, strong) UIButton *homeButton;

@property (nonatomic, strong) UserInfo *userInfo;


/** topimage **/
@property(nonatomic,strong) UIImageView *topbackImage;

@end

@implementation AccountInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self masLayoutSubview];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self setNavigationStyle];

}

- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}

- (void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    
}

- (void)onLeftButtonClick:(id)sender{
    
    if (self.indextag == 0) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }else if (self.indextag == 1){
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
#pragma mark - --------------------------UITableView dataSource--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.settingPlist.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.settingPlist[section] count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        
    }
    
    
    switch (indexPath.row) {
        case 0://性别
        {
            SexTableViewCell *yearCell = [tableView dequeueReusableCellWithIdentifier:PICKERCELL];
            if (yearCell == nil) {
                yearCell = [[SexTableViewCell alloc]init];
                yearCell.textLabel.text = self.settingPlist[indexPath.section][indexPath.row][@"title"];
                
            }
            if ([self.userInfo.sex isEqualToString:@"1"]) {//男
                yearCell.detailTextLabel.text = @"男";
            }else if ([self.userInfo.sex isEqualToString:@"2"]){//女
                yearCell.detailTextLabel.text = @"女";
            }
            
            return yearCell;
            break;
        }
        case 1://生日
        {
            YearToDayTableViewCell *yearCell = [tableView dequeueReusableCellWithIdentifier:kYearToDayCellIdentifier];
            if (yearCell == nil) {
                yearCell = [[YearToDayTableViewCell alloc]init];
                yearCell.textLabel.text = self.settingPlist[indexPath.section][indexPath.row][@"title"];
            }
            yearCell.detailTextLabel.text = self.userInfo.birth;
            
            return yearCell;
            break;
        }
        case 2://身高
        {
            HeightTableViewCell *heightCell = [tableView dequeueReusableCellWithIdentifier:PICKERCELL];
            if (heightCell == nil) {
                heightCell = [[HeightTableViewCell alloc]init];
                heightCell.textLabel.text = self.settingPlist[indexPath.section][indexPath.row][@"title"];
                
            }
            heightCell.detailTextLabel.text = [NSString stringWithFormat:@"%@cm",self.userInfo.height];
            
            return heightCell;
            break;
        }
        case 3://体重
        {
            WeightTableViewCell *weightCell = [tableView dequeueReusableCellWithIdentifier:PICKERCELL];
            if (weightCell == nil) {
                weightCell = [[WeightTableViewCell alloc]init];
                weightCell.textLabel.text = self.settingPlist[indexPath.section][indexPath.row][@"title"];
                
            }
            weightCell.detailTextLabel.text = [NSString stringWithFormat:@"%@kg",self.userInfo.weight];
            
            return weightCell;
            break;
        }
        default:
            break;
    }
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 55.f;
    
}

#pragma mark - --------------------------UITableView delegate--------------------------
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    [cell becomeFirstResponder];
    switch (indexPath.row) {
        case 0://性别
        {
            SexTableViewCell *sexCell = (SexTableViewCell *)cell;
            sexCell.select_block = ^(NSArray *selectArray){
                NSString *sexTag;
                if ([selectArray[0] isEqualToString:@"男"]) {
                    sexTag = @"1";
                }else{
                    sexTag = @"2";
                }
                SetUserInfoApi *setuserinfo = [[SetUserInfoApi alloc] initWithInfo:@{@"sex":sexTag}];
                [self startWithYTKRequest:setuserinfo completionBlockWithSuccess:^(YTKBaseRequest *request) {
                    
                    [self getUserInfo_block:^(UserInfo *userInfo) {
                        
                        self.userInfo = userInfo;
                        [self.tableView reloadData];
                        
                    }];
                    
                    
                } failure:nil];
            };
            break;
        }
        case 1://生日
        {
            YearToDayTableViewCell *yearCell = (YearToDayTableViewCell *)cell;
            yearCell.select_block = ^(NSDate *yearDate){
          
                

                NSString * dateStr = [yearDate formattedDateWithStyle: NSDateFormatterFullStyle];
                
                NSLog(@"%@", dateStr); // 输出: 2015年9月25日 星期五
                
                dateStr =  [yearDate formattedDateWithFormat:@"yyyy-MM-dd"];
                NSLog(@"%@", dateStr); // 输出: 2015年9月25日 星期五
                SetUserInfoApi *setuserinfo = [[SetUserInfoApi alloc] initWithInfo:@{@"birth":dateStr}];
                [self startWithYTKRequest:setuserinfo completionBlockWithSuccess:^(YTKBaseRequest *request) {
                    
                    [self getUserInfo_block:^(UserInfo *userInfo) {
                        
                        self.userInfo = userInfo;
                        [self.tableView reloadData];
                        
                    }];
                    
                    
                } failure:nil];
                
                
            };
            
            
            break;
        }
        case 2://身高
        {
            HeightTableViewCell *heightCell = (HeightTableViewCell *)cell;
            
            heightCell.select_block = ^(NSArray *heightArray){
                NSString *height = [NSString stringWithFormat:@"%@",heightArray[0]];
                
                SetUserInfoApi *setuserinfo = [[SetUserInfoApi alloc] initWithInfo:@{@"height":height}];
                [self startWithYTKRequest:setuserinfo completionBlockWithSuccess:^(YTKBaseRequest *request) {
                    
                    [self getUserInfo_block:^(UserInfo *userInfo) {
                        
                        self.userInfo = userInfo;
                        [self.tableView reloadData];
                        
                    }];
                    
                    
                } failure:nil];
                
                
            };
            break;
        }
        case 3://体重
        {
            WeightTableViewCell *weightCell = (WeightTableViewCell *)cell;
            weightCell.select_block = ^(NSArray *weightArray){
                NSString *weight = [NSString stringWithFormat:@"%@",weightArray[0]];
                SetUserInfoApi *setuserinfo = [[SetUserInfoApi alloc] initWithInfo:@{@"weight":weight}];
                [self startWithYTKRequest:setuserinfo completionBlockWithSuccess:^(YTKBaseRequest *request) {
                    
                    [self getUserInfo_block:^(UserInfo *userInfo) {
                        
                        self.userInfo = userInfo;
                        [self.tableView reloadData];
                        
                    }];
                    
                    
                } failure:nil];
                
                
            };
            
            break;
        }
        default:
            break;
    }
}

- (void)selectImageEvent{
    
    [self createActionSheetWithImagePath:^(NSString *imagePath) {
        
        SetUserInfoApi *setuserinfo = [[SetUserInfoApi alloc] initWithInfo:@{@"image":imagePath}];
        [self startWithYTKRequest:setuserinfo completionBlockWithSuccess:^(YTKBaseRequest *request) {
            
            [self getUserInfo_block:^(UserInfo *userInfo) {
                
                self.userInfo = userInfo;
                [self.iconButton sd_setImageWithURL:[NSURL URLWithString:self.userInfo.image] forState:UIControlStateNormal];
            }];
            
            
        } failure:nil];
        
    
     
    }];
    
}

- (void)editNameAction{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改名字"
                                                                   message:@""
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
    }];
    
    __weak typeof(alert) alere = alert;

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {}];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
    if ([alere.textFields.firstObject.text length]<=6 && [alere.textFields.firstObject.text length]>0){
        
        SetUserInfoApi *setuserinfo = [[SetUserInfoApi alloc] initWithInfo:@{@"nickname":alere.textFields.firstObject.text}];
        [self startWithYTKRequest:setuserinfo completionBlockWithSuccess:^(YTKBaseRequest *request) {
            
            [self getUserInfo_block:^(UserInfo *userInfo) {
                
                self.userInfo = userInfo;
                self.nicknameLabel.text = self.userInfo.nickname;
            }];
            
            
        } failure:nil];

    }else{
        
        [SVProgressHUD showErrorWithStatus:@"输入名称过长或输入了非法字符"];

    }
                                                              
               
                                                          
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:confirmAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}


- (void)setNavigationStyle{
    
    [self setNavigationTitle:@"个人资料" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self hideNavigationBottomLine];
    self.homeButton.hidden = YES;
    self.userInfo = [KaiseruserDataGit loadUserInfo];
    _nicknameLabel.text = self.userInfo.nickname;
    if ([self.userInfo.image isEqualToString:@""]) {
        
        [_iconButton setImage:[UIImage imageNamed:@"bg_head_portrait"] forState:UIControlStateNormal];
        
    }else{
        
        [_iconButton sd_setImageWithURL:[NSURL URLWithString:self.userInfo.image] forState:UIControlStateNormal];
        
    }
    [self.tableView reloadData];
    
}

- (NSArray *)settingPlist{
    
    if (!_settingPlist) {
        
        _settingPlist = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"AccountInfoSetting" ofType:@"plist"]];
        
    }
    return _settingPlist;
}

- (UIView *)topView{
    
    if (!_topView) {
        
        __weak UIView *superView = self.view;
        _topView = [[UIView alloc]init];
        [superView addSubview:_topView];
        _topView.backgroundColor = [UIColor colorWithHexString:@"231815"];
        
    }
    
    return _topView;
    
}

- (UIButton *)iconButton{
    
    if (!_iconButton) {
        
        __weak UIView *superView = self.view;
        _iconButton = [[UIButton alloc]init];
        [superView addSubview:_iconButton];
    
        [_iconButton setBackgroundColor:[UIColor colorWithRed:63/255.0 green:47/255.0 blue:44/255.0 alpha:1]];
        _iconButton.layer.cornerRadius = 35.f;
        _iconButton.layer.masksToBounds = YES;
        _iconButton.layer.borderColor = [UIColor whiteColor].CGColor;
        _iconButton.layer.borderWidth = 2.f;
        [_iconButton addTarget:self action:@selector(selectImageEvent) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return _iconButton;
    
}

- (UILabel *)nicknameLabel{
    
    if (!_nicknameLabel) {
        
        __weak UIView *superView = self.view;
        _nicknameLabel = [[UILabel alloc]init];
        [superView addSubview:_nicknameLabel];
        [_nicknameLabel setFont:[UIFont systemFontOfSize:15.f]];
        _nicknameLabel.textColor = [UIColor whiteColor];
        
    }
    
    return _nicknameLabel;
    
}

- (UIButton *)editNameButton{
    
    if (!_editNameButton) {
        
        __weak UIView *superView = self.view;
        _editNameButton = [[UIButton alloc]init];
        //        _editNameButton.frame = CGRectMake(0, 0, 60, 60);
        [superView addSubview:_editNameButton];
        
        [_editNameButton setImage:[UIImage imageNamed:@"icon_edit"] forState:UIControlStateNormal];
        [_editNameButton addTarget:self action:@selector(editNameAction) forControlEvents:UIControlEventTouchUpInside];
        _editNameButton.contentEdgeInsets = UIEdgeInsetsMake(50, 0, 0, 50);
        
        
    }
    
    return _editNameButton;
    
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        //        _tableView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        self.view.backgroundColor = [UIColor whiteColor];
    }
    
    return _tableView;
    
}

- (UIButton *)homeButton{
    
    if (!_homeButton) {
        
        _homeButton = [[UIButton alloc]init];
        [self.view addSubview:_homeButton];
        [_homeButton.titleLabel setFont:[UIFont systemFontOfSize:13.0f]];
        [_homeButton setTitle:@"进入首页" forState:UIControlStateNormal];
        [_homeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_homeButton setBackgroundImage:[UIImage imageNamed:@"14_but_download"] forState:UIControlStateNormal];
        
    }
    
    return _homeButton;
    
}

- (UIImageView *)topbackImage{
    
    if (!_topbackImage) {
        
        __weak UIView *superView = self.view;
        _topbackImage = [[UIImageView alloc] init];
        _topbackImage.image = [UIImage imageNamed:@"bg_data"];
        [superView addSubview:_topbackImage];
        
    }
    return _topbackImage;
}

- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    __weak typeof(self) weakself = self;
    [self.topView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(superView.mas_top);
        make.left.mas_equalTo(superView.mas_left);
        make.right.mas_equalTo(superView.mas_right);
        make.height.mas_equalTo(80.f);
        
    }];
    
    
    [self.topbackImage mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(weakself.topView.mas_bottom).mas_offset(-10);
        make.centerX.mas_equalTo(superView.mas_centerX);
        
        
    }];
    
    [self.nicknameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(weakself.topView.mas_bottom).mas_offset(-10);
        make.centerX.mas_equalTo(superView.mas_centerX);
        
    }];
    

    
    [self.iconButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakself.topbackImage.mas_left).mas_offset(20);
        make.height.and.width.mas_equalTo(70.f);

        make.centerY.mas_equalTo(weakself.topbackImage.mas_top).mas_offset(10);
        
    }];
    
   
    
    [self.editNameButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.nicknameLabel.mas_right).mas_offset(kspaceWidth);
        make.bottom.mas_equalTo(self.nicknameLabel.mas_bottom);
        
    }];
    
    
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.topbackImage.mas_bottom).mas_offset(40);
        make.left.mas_equalTo(superView.mas_left).mas_offset(kspaceWidth);
        make.right.mas_equalTo(superView.mas_right).mas_offset(-kspaceWidth);
        make.bottom.mas_equalTo(superView.mas_bottom);
        
    }];
    [self.homeButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.mas_equalTo(superView.mas_bottom).mas_offset(-50);
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.left.mas_equalTo(superView.mas_left).mas_offset(30);
        make.right.mas_equalTo(superView.mas_right).mas_offset(-30);
        
    }];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
